<template>
  <div class="user-list">
    <el-card>
      <!-- 头部结构 -->
      <div slot="header">
        <el-form :model="filterParams" ref="form" :inline="true">
        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="filterParams.phone" placeholder="请输入手机号" clearable></el-input>
        </el-form-item>
        <el-form-item label="注册时间:" prop="rangeData">
          <el-date-picker
            v-model="filterParams.rangeData"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" :disabled="isLoading">查询</el-button>
          <el-button @click="onreset" :disabled="isLoading" type="primary">重置</el-button>
        </el-form-item>
        </el-form>
      </div>
      <!-- 主体结构 -->
      <el-table
        :data="users"
        style="width: 100%"
         v-loading="isLoading">
        <el-table-column
          prop="id"
          label="用户id"
          width="150">
        </el-table-column>
        <el-table-column
         prop="portrait"
          label="头像"
          width="100">
          <template slot-scope="scope">
            <img width="30px" :src="scope.row.portrait || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'">
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="用户名">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="注册时间">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="ENABLE"
                inactive-value="DISABLE"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleForbidUser(scope.row)"
              >
              </el-switch>
        </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作">
          <template slot-scope="scope">
            <el-button
            type="text"
              size="mini"
              @click="handleSelectRole(scope.row)">
              分配角色
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 设置分配角色 dialoag组件结构 -->
      <el-dialog title="分配角色" :visible.sync="dialogFormVisible">
        <el-form>
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-select v-model="roleIdList" multiple placeholder="请选择">
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAllocRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页结构 -->
      <el-pagination style="float:right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="filterParams.currentPage"
        :page-sizes="[10, 15, 20]"
        :page-size="filterParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
        :disabled="isLoading">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getUserPages } from '@/services/user'
import { getAllRole, allocateUserRoles, getUserRoles } from '@/services/role'
export default {
  name: 'UserList',
  data () {
    return {
      // 为顶部搜索功能设置基础配置项
      filterParams: {
        currentPage: 1,
        pageSize: 10,
        // 手机号
        phone: '',
        // 开始时间
        startCreateTime: '',
        // 结束时间
        endCreateTime: '',
        // 日期范围
        rangeDate: []
      },
      // 所有用户
      users: [],
      // 数据总条数
      totalCount: 0,
      // 控制加载状态
      isLoading: false,
      // 控制弹框是否显示
      dialogFormVisible: false,
      formLabelWidth: '120px',
      // 下拉菜单数据
      roles: [],
      // 选中选项的Id组成的数组
      roleIdList: [],
      // 当前要进行角色分配用户的ID
      currentRoleID: ''
    }
  },
  created () {
    this.loadUsers()
  },
  methods: {
    // 提交分配的角色点击确定按钮
    async handleAllocRole () {
      // this.dialogFormVisible = false
      const { data } = await allocateUserRoles({
        userId: this.currentRoleID,
        roleIdList: this.roleIdList
      })
      // console.log(data)
      if (data.code === '000000') {
        this.$message.success('分配角色成功')
        this.dialogFormVisible = false
      }
    },
    // 加载用户相关信息
    async loadUsers () {
      // this.isLoading = true
      const { rangeDate } = this.filterParams
      if (rangeDate && rangeDate.length) {
        this.filterParams.startCreateTime = rangeDate[0]
        this.filterParams.endCreateTime = rangeDate[1]
      } else {
        this.filterParams.startCreateTime = ''
        this.filterParams.endCreateTime = ''
      }
      const { data } = await getUserPages(this.filterParams)
      // console.log(data)
      this.users = data.data.records
      this.totalCount = data.data.total
      this.isLoading = false
    },
    // 分配角色按钮进行的操作
    async handleSelectRole (userInfo) {
      this.currentRoleID = userInfo.id
      // console.log(this.currentRoleID)
      this.dialogFormVisible = true
      // 请求所有角色列表数据
      const { data } = await getAllRole()
      // console.log(data)
      if (data.code === '000000') {
        this.roles = data.data
      }
      // 请求当前用户已分配的角色信息
      const { data: data2 } = await getUserRoles(this.currentRoleID)
      // console.log(data2)
      if (data2.code === '000000') {
        this.roleIdList = data2.data.map(item => item.id)
      }
    },
    // 每页显示的条数变化时触发
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.filterParams.pageSize = val
      // 修改了每页显示的条数,当前页面回到初始值 current: 1,
      this.filterParams.currentPage = 1
      this.loadUsers()
    },
    // 页数发生变化时触发
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.filterParams.currentPage = val
      this.loadUsers()
    },
    handleQuery () {
      this.loadUsers()
    },
    onreset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped></style>
